#include <iostream>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <functional>

using func_t = std::function<void(void)>;

void LogService()
{
    std::cout << "日志服务..." << std::endl;
}

void SqlService()
{
    std::cout << "数据库服务..." << std::endl;
}

void WebService()
{
    std::cout << "网页服务..." << std::endl;
}

void Service()
{
    std::vector<func_t> service;
    service.push_back(LogService);
    service.push_back(SqlService);
    service.push_back(WebService);

    for(auto& ser: service)
        ser();
}

void SetNoBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        std::cout << "errno: " << errno << "reason: " << strerror(errno) << std::endl;
        exit(-1);
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    SetNoBlock(0);
    char buffer[64];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        int n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read file end..." << std::endl;
            break;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 其他业务处理
                std::cout << "Date haven't ready..." << std::endl;
                Service();
                sleep(1);
                continue;
            }

            std::cout << "errno: " << errno << " reason: " << strerror(errno) << std::endl;
            // break;
        }
    }
    return 0;
}